﻿#include "frmmain.h"
#include "ui_frmmain.h"
#include <QHBoxLayout>
#include "quiwidget.h"
#include "iconfont.h"
#include "appinit.h"
#include "framelesshelper.h"
#include "maindeviceform.h"
#include "canctrl.h"
#include "savelog.h"
#include "setparamsdlg.h"
#include "candeviceform.h"
#include "selfform.h"
#include "alarmdashboard.h"
#include "mainscene.h"
//#include <QIcon>

frmMain::frmMain(QWidget *parent) : QWidget(parent), ui(new Ui::frmMain)
{
    ui->setupUi(this);

    //setWindowIcon(QIcon(":/image/icon.ico"));

    this->initForm();
    this->initText();
    this->initNav();
    this->initLeftNav();
    this->initIcon();
    this->initLeftIcon();
    this->initLogForm();
    QUIHelper::setFormInCenter(this);
    on_btnMenu_Max_clicked();

    qDebug() << ui->widgetTop->width();
    qDebug() << ui->labLogoCn->fontInfo().pixelSize();
    qDebug() << ui->labLogoCn->fontInfo().family();

    m_canthread = new CANThread();
    connect(MainSceneIns,MainScene::sendData,m_canthread,CANThread::sendData);
    connect(MainDeviceFormIns,MainDeviceForm::sendData,m_canthread,CANThread::sendData);
    m_canthread_1 = new CANThread();
}

frmMain::~frmMain()
{
    delete ui;
}

bool frmMain::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonDblClick) {
        //双击标题栏最大化
        if (watched == ui->widgetTop) {
            on_btnMenu_Max_clicked();
        }
    }

    return QWidget::eventFilter(watched, event);
}

void frmMain::initForm()
{
    ui->widgetLeft->setProperty("nav", "left");
    ui->widgetLeft->setFixedWidth(150);

    ui->widgetMain->setProperty("form", true);

    ui->widgetTop->setProperty("form", "title");
    ui->widgetTop->setFixedHeight(80);

    //ui->bottomWidget->setProperty("form","bottom");
    ui->bottomWidget->setFixedHeight(25);

    this->setProperty("form", true);
//    this->setProperty("canMove", true);
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);
    ui->widgetTop->installEventFilter(this);
    ui->labLogoBg->installEventFilter(this);

    //设置右上角菜单,图形字体
    IconHelper::Instance()->setIcon(ui->btnMenu_Min, QUIConfig::IconMin);
    IconHelper::Instance()->setIcon(ui->btnMenu_Max, QUIConfig::IconNormal);
    IconHelper::Instance()->setIcon(ui->btnMenu_Close, QUIConfig::IconClose);

    //无边框可拉伸类
    frameless = new FramelessHelper(this);
    //激活当前窗体
    frameless->activateOn(this);
    //设置窗体的标题栏高度
    frameless->setTitleHeight(ui->widgetTop->height());
    //设置窗体可移动
    frameless->setWidgetMovable(true);
    //设置窗体可缩放
    frameless->setWidgetResizable(true);

    //设置底部状态栏
    ui->bottomWidget->setVersion("V1.0.0.0");
    ui->bottomWidget->setCurrentUserName("王磊");
    ui->bottomWidget->setCurrentUserType("开发员");
    ui->bottomWidget->setFontName(QUIConfig::FontName);
    int fontSize = (QUIConfig::FontSize > 12 ? QUIConfig::FontSize - 1 : QUIConfig::FontSize);
    ui->bottomWidget->setFontSize(fontSize);
    ui->bottomWidget->setLineFixedWidth(true);
    ui->bottomWidget->start();

    //添加换肤菜单
    QStringList styleNames;
    styleNames << "银色" << "蓝色" << "浅蓝色" << "深蓝色" << "灰色" << "浅灰色" << "深灰色" << "黑色"
               << "浅黑色" << "深黑色" << "PS黑色" << "黑色扁平" << "白色扁平" << "蓝色扁平" << "紫色" << "黑蓝色" << "视频黑";
    this->setContextMenuPolicy(Qt::ActionsContextMenu);

    foreach (QString styleName, styleNames) {
        QAction *action = new QAction(styleName, this);
        connect(action, SIGNAL(triggered(bool)), this, SLOT(initStyle()));
        this->addAction(action);
    }
}

void frmMain::initText()
{
    //从配置文件读取logo名称
    ui->labLogoCn->setText("高压共轨能源系统");
    ui->labLogoEn->setText("High-pressure common rail energy system");
    this->setWindowTitle(ui->labLogoCn->text());

    //设置标题+版本+版权
    ui->bottomWidget->setTitle("高压共轨能源系统");
    ui->bottomWidget->setAuthor("广东中合聚能科技有限公司");
}

void frmMain::initNav()
{
    MainDeviceFormIns->setProperty("form","true");
    QHBoxLayout *hLayout = new QHBoxLayout(ui->frame_mainstate);
    hLayout->addWidget(MainDeviceFormIns);
    hLayout->setMargin(1);
    ui->frame_mainstate->setLayout(hLayout);

    QHBoxLayout *vLayout = new QHBoxLayout(this);
    vLayout->addWidget(AlarmDashboardIns);
    vLayout->setMargin(5);
    ui->groupBox_alarm->setLayout(vLayout);

//    frmConfig *config = new frmConfig;
//    ui->stackedWidget->addWidget(config);

    QList<QString> texts;
    btns << ui->btnStart << ui->btnStop;
    texts << "启动CAN" << "断开CAN";

    for (int i = 0; i < btns.count(); i++) {
        QPushButton *btn = (QPushButton *)btns.at(i);
        btn->setIconSize(QSize(25, 20));
        btn->setFixedWidth(115);
        btn->setCheckable(true);
        btn->setText(texts.at(i));
        connect(btn, SIGNAL(clicked(bool)), this, SLOT(buttonClicked()));
    }
}

void frmMain::initLeftNav()
{
    QList<QString> texts;
    leftbtns << ui->btnExternal << ui->btnInternal;
    texts << "外 部 数 据" << "内 部 数 据";

    ui->stackedWidget->insertWidget(0,CANDeviceFormIns);
    ui->stackedWidget->insertWidget(1,SelfFormIns);

    for (int i = 0; i < leftbtns.count(); i++) {
        QPushButton *btn = (QPushButton *)leftbtns.at(i);
        btn->setIconSize(QSize(30, 20));
        btn->setCheckable(true);
        btn->setText(texts.at(i) + "  ");
        connect(btn, SIGNAL(clicked(bool)), this, SLOT(leftButtonClicked()));
    }

    ui->btnExternal->click();
}

void frmMain::initIcon()
{
    //如果logo图片不存在则隐藏标签,否则显示logo图片
    ui->labLogoBg->setAlignment(Qt::AlignCenter);
    QPixmap pixLogo(":/image/icon.png");
    if (pixLogo.isNull()) {
        //ui->labLogoBg->setVisible(false);
        //设置图形字体作为logo
        int size = 60;
        ui->labLogoBg->setFixedWidth(size + 20);
        IconFont::Instance()->setIcon(ui->labLogoBg, 0xe708, size);
    } else {
        int size = 150;
        ui->labLogoBg->setFixedWidth(size + 20);
        pixLogo = pixLogo.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->labLogoBg->setPixmap(pixLogo);
    }

    //从图形字体库中设置图标
    ui->btnStart->setIcon(IconHelper::Instance()->getPixmap(QUIConfig::TextColor, 0xf01d, 20, 20, 20));
    ui->btnStop->setIcon(IconHelper::Instance()->getPixmap(QUIConfig::TextColor, 0xf28e, 20, 20, 20));
}

void frmMain::initLeftIcon()
{
    //从图形字体库中设置图标
    ui->btnExternal->setIcon(IconFont::Instance()->getPixmap(QUIConfig::TextColor, 0xe60d, 20, 30, 20));
    ui->btnInternal->setIcon(IconFont::Instance()->getPixmap(QUIConfig::TextColor, 0xe9c1, 20, 30, 20));
}

void frmMain::buttonClicked()
{
    QPushButton *btn = (QPushButton *)sender();
    if(btn == ui->btnStart) {
        //启动CAN
        SetParamsDlgIns->exec();

        int deviceType = SetParamsDlgIns->GetCANType();
        int debicIndex = SetParamsDlgIns->GetDeviceIndex();
        int baundRate = SetParamsDlgIns->GetBaundRate();
        int debicCom = SetParamsDlgIns->GetCANCom();

        bool dev = m_canthread->openCAN(deviceType,debicIndex,baundRate,debicCom);
        if(dev)
        {
            ui->lightButton->setBgColor(QColor(68,195,119));
            m_canthread->start();
        }
    }
    else if(btn == ui->btnStop) {
        //断开CAN
        m_canthread->stop();
        m_canthread->closeCAN();
        ui->lightButton->setBgColor(QColor(255,0,0));
    }


    //取消其他按钮选中
    foreach (QPushButton *b, btns) {
        b->setChecked(b == btn);
    }
}

void frmMain::leftButtonClicked()
{
    QPushButton *btn = (QPushButton *)sender();
    int index = leftbtns.indexOf(btn);
    ui->stackedWidget->setCurrentIndex(index);

    //取消其他按钮选中
    foreach (QPushButton *b, leftbtns) {
        b->setChecked(b == btn);
    }
}

void frmMain::initStyle()
{
    QAction *act = (QAction *)sender();
    QString name = act->text();
    QString qssFile = ":/qss/lightblue.css";

    if (name == "银色") {
        qssFile = ":/qss/silvery.css";
    } else if (name == "蓝色") {
        qssFile = ":/qss/blue.css";
    } else if (name == "浅蓝色") {
        qssFile = ":/qss/lightblue.css";
    } else if (name == "深蓝色") {
        qssFile = ":/qss/darkblue.css";
    } else if (name == "灰色") {
        qssFile = ":/qss/gray.css";
    } else if (name == "浅灰色") {
        qssFile = ":/qss/lightgray.css";
    } else if (name == "深灰色") {
        qssFile = ":/qss/darkgray.css";
    } else if (name == "黑色") {
        qssFile = ":/qss/black.css";
    } else if (name == "浅黑色") {
        qssFile = ":/qss/lightblack.css";
    } else if (name == "深黑色") {
        qssFile = ":/qss/darkblack.css";
    } else if (name == "PS黑色") {
        qssFile = ":/qss/psblack.css";
    } else if (name == "黑色扁平") {
        qssFile = ":/qss/flatblack.css";
    } else if (name == "白色扁平") {
        qssFile = ":/qss/flatwhite.css";
    } else if (name == "蓝色扁平") {
        qssFile = ":/qss/flatblue.css";
    } else if (name == "紫色") {
        qssFile = ":/qss/purple.css";
    } else if (name == "黑蓝色") {
        qssFile = ":/qss/blackblue.css";
    } else if (name == "视频黑") {
        qssFile = ":/qss/blackvideo.css";
    }

    AppInit::Instance()->initStyle(qssFile);
    emit changeStyle();
}

void frmMain::on_btnMenu_Min_clicked()
{
    this->showMinimized();
}

void frmMain::on_btnMenu_Max_clicked()
{
    static bool max = false;
    static QRect location = this->geometry();

    if (max) {
        this->setGeometry(location);
    } else {
        location = this->geometry();
        this->setGeometry(qApp->desktop()->availableGeometry());
    }

    IconHelper::Instance()->setIcon(ui->btnMenu_Max, max ? QUIConfig::IconNormal : QUIConfig::IconMax);
    this->setProperty("canMove", max);
    max = !max;
    frameless->setWidgetMovable(!max);
    frameless->setWidgetResizable(!max);
}

void frmMain::on_btnMenu_Close_clicked()
{
    this->close();
}


void frmMain::initLogForm()
{
    ui->frame_log->hide();

    countLog = 0;

    //添加消息类型
    QStringList types,datas;
    types << "Debug" << "Info" << "Warning" << "Critical" << "Fatal";
    datas << "1" << "2" << "4" << "8" << "16";

    //添加消息类型到列表用于勾选设置哪些类型需要重定向
    int count = types.count();
    for(int i = 0; i < count; ++i)
    {
        QListWidgetItem *item = new QListWidgetItem;
        item->setText(types.at(i));
        item->setData(Qt::UserRole,datas.at(i));
        item->setCheckState(Qt::Checked);
        ui->listType->addItem(item);
    }

    //添加日志文件大小下拉框
    ui->cboxSize->addItem("不启用",0);
    ui->cboxSize->addItem("5kb",5);
    ui->cboxSize->addItem("10kb",10);
    ui->cboxSize->addItem("30kb",30);
    ui->cboxSize->addItem("1mb",1024);

    ui->cboxRow->addItem("不启用", 0);
    ui->cboxRow->addItem("100条", 100);
    ui->cboxRow->addItem("500条", 500);
    ui->cboxRow->addItem("2000条", 2000);
    ui->cboxRow->addItem("10000条", 10000);

    //设置是否开启日志上下文打印，比如行号、函数等
    SaveLogIns->SetUseContext(false);
    //设置文件存储目录
    SaveLogIns->SetPath("D:/BMS/Log");

    ui->ckSave->setChecked(true);
    ui->txtMain->setReadOnly(true);

    connect(SaveLogIns,&SaveLog::flushLogUI,this,&frmMain::on_flushLogUI);
}



void frmMain::frmMain::on_flushLogUI(const QString &msg)
{
    if(countLog >= 100)
    {
        countLog = 0;
        ui->txtMain->clear();
    }

    ui->txtMain->append(msg);
    countLog++;
}

void frmMain::on_cboxSize_currentIndexChanged(int index)
{
    int size = ui->cboxSize->itemData(index).toInt();
    SaveLogIns->SetMaxSize(size);
}


void frmMain::on_cboxRow_currentIndexChanged(int index)
{
    int row = ui->cboxRow->itemData(index).toInt();
    SaveLogIns->SetMaxRow(row);
}


void frmMain::on_ckSave_stateChanged(int arg1)
{
    if(arg1 == 0)
    {
        SaveLogIns->Stop();
    }
    else
    {
        SaveLogIns->Start();
    }
}


void frmMain::on_listType_itemPressed(QListWidgetItem *item)
{
    //切换选中行状态
    item->setCheckState(item->checkState() == Qt::Checked ? Qt::Unchecked : Qt::Checked);

    //找到所有勾选的类型进行设置
    quint8 types = 0;
    int count = ui->listType->count();
    for(int i = 0; i < count; ++i)
    {
        QListWidgetItem *item = ui->listType->item(i);
        if(item->checkState() == Qt::Checked)
        {
            types += item->data(Qt::UserRole).toInt();
        }
    }

    SaveLogIns->SetMsgType((MsgType)types);
}


void frmMain::on_btnLogClear_clicked()
{
   ui->txtMain->clear();
}

